package com.gaoyi.basemodule.baseUtil;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.FileProvider;
import androidx.exifinterface.media.ExifInterface;
import androidx.fragment.app.FragmentActivity;

import com.gaoyi.basemodule.R;

import java.io.File;
import java.io.IOException;

/**
 * 跳转到系统应用类
 */
public class SystemUtils {

    private static volatile SystemUtils instance;

    public static SystemUtils getInstance() {
        if (instance == null) {
            synchronized (SystemUtils.class) {
                if (instance == null) {
                    instance = new SystemUtils();
                }
            }
        }
        return instance;
    }

    private String mImgUrl;

    /**
     * 检查并获取权限，跳转到系统相机
     */
    public void toCamera(FragmentActivity activity, ActivityResultLauncher<String[]> permissionsResult, ActivityResultLauncher<Intent> cameraResult) {
        if (PermissionUtils.addPermission(activity, new String[]{Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE}, permissionsResult)) {
            toCamera(activity, cameraResult);
        }
    }

    /**
     * 跳转到系统相机
     */
    public void toCamera(Activity activity, ActivityResultLauncher<Intent> resultLauncher) {
        PackageManager pm = activity.getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            ToastUtil.showToast(R.string.no_camera);
            return;
        }
        try {
            String imgName = ImageUtil.getImgName();
            File photoFile = new File(activity.getExternalCacheDir(), imgName);
            File parentFile = photoFile.getParentFile();
            if (!parentFile.exists()) parentFile.mkdirs();
            if (photoFile.exists()) photoFile.delete();
            photoFile.createNewFile();
            mImgUrl = photoFile.getAbsolutePath();
            Uri imgUri = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
                    FileProvider.getUriForFile(activity, activity.getPackageName() + ".provider", photoFile)
                    : Uri.fromFile(photoFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            resultLauncher.launch(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(R.string.no_camera);
        }
    }

    /**
     * 获取拍照后的图片
     *
     * @param isResize 是否压缩图片大小
     */
    public String getCameraResult(FragmentActivity activity, boolean isResize) {
        Bitmap bitmap = null;
        if (isResize) {
            bitmap = BitmapUtils.getInstance().resizePath(mImgUrl);
        }
        int angle = getCameraAngle(mImgUrl);
        if (angle != 0) {
            if (bitmap == null) {
                bitmap = BitmapUtils.getInstance().url2Bitmap(mImgUrl);
            }
            bitmap = BitmapUtils.getInstance().rotatingBitmap(bitmap, angle);
        }
        return bitmap == null ? mImgUrl : BitmapUtils.getInstance().bitmap2Url(activity, bitmap, mImgUrl);
    }

    /**
     * 获取图片旋转角度
     */
    private int getCameraAngle(String imgUrl) {
        int angle = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(imgUrl);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    angle = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    angle = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return angle;
    }

    private Camera.CameraInfo info;
    private int angle;

    public int getAngle() {
        if (info == null) {
            info = new Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(0, info);
            angle = info.orientation;
        }
        return angle;
    }

    /**
     * 跳转到系统选择文件
     *
     * @param resultLauncher
     */
    public void toFile(ActivityResultLauncher<Intent> resultLauncher) {
        try {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            resultLauncher.launch(intent);
        } catch (Exception e) {
            ToastUtil.showToast(R.string.no_file);
        }
    }

    public String getFileResult(Context context, ActivityResult result) {
        Intent data = result.getData();
        if (data == null) return null;
        return FileUtils.getInstance().getFilePathByUri(context, data.getData());
    }

    /**
     * 跳转至图库
     */
    public void toGallery(ActivityResultLauncher<Intent> resultLauncher) {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            resultLauncher.launch(intent);
        } catch (Exception e) {
            ToastUtil.showToast(R.string.no_gallery);
        }
    }

    /**
     * 图片剪裁
     *
     * @param uri 图片uri
     */
    public Intent pictureCropping(Uri uri) {
        // 调用系统中自带的图片剪裁
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        // 返回裁剪后的数据
        intent.putExtra("return-data", true);
        return intent;
    }

}
